package com.linsen.core.rabbitmq.service;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;

import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyong
 * @date 2023/3/13
 */
public class RabbitMQOptions {
    private static final String DELAYED_DURATION_HEADER_NAME = "x-delay";

    private static final long DEFAULT_TIME_UNIT = 1000 * 60;

    public static Message delay(Message message, TimeUnit timeUnit, long timeout) {
        MessageProperties messageProperties = message.getMessageProperties();
        messageProperties.setHeader(DELAYED_DURATION_HEADER_NAME, timeUnit(timeUnit, timeout));
        return message;
    }

    private static long timeUnit(TimeUnit timeUnit, long timeout) {
        long time;
        switch (timeUnit) {
            case DAYS:
                time = timeout * 1000 * 60 * 60 * 24;
                break;
            case HOURS:
                time = timeout * 1000 * 60 * 60;
                break;
            case MINUTES:
                time = timeout * 1000 * 60;
                break;
            case SECONDS:
                time = timeout * 1000;
                break;
            case MILLISECONDS:
                time = timeout;
                break;
            default:
                time = timeout * DEFAULT_TIME_UNIT;
        }
        return time;
    }
}
